package com.chatdating.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chatdating.entity.*;
import com.chatdating.entity.dto.CommentDto;
import com.chatdating.entity.dto.PostCreateDto;
import com.chatdating.entity.pojo.Result;
import com.chatdating.mapper.UserMapper;
import com.chatdating.service.CommentService;
import com.chatdating.service.LikeService;
import com.chatdating.service.PostService;
import com.chatdating.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("post")
public class PostController {

    @Autowired
    private PostService postService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(PostController.class);
    @Autowired
    private UserMapper userMapper;

    /**
     * 发布帖子
     * @param postDto
     * @return
     */
    @RequestMapping("save")
    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<Long> createPost(@RequestBody PostCreateDto postDto) {
        // 处理图片上传
        //List<String> imageUrls = postService.uploadImages(postDto.getImages());

        String[] images = postDto.getImages();

        User byName = userMapper.findByName(postDto.getAuthorName());
        int id = byName.getId();

        // 构建Post对象
        Post post = new Post();
        post.setContent(postDto.getContent());
        post.setAuthorId(id);
        post.setUserHead(postDto.getUserHead());
        post.setAuthorName(postDto.getAuthorName());
        post.setImageUrls(String.join(";", images)); // 用分号拼接URL

        postService.save(post);
        return Result.success(post.getId());
    }

    @GetMapping("/{id}")
    public Result<Post> getPost(@PathVariable Long id) {
        Post post = postService.getPostWithDetails(id);
        return post != null ?
                Result.success(post) :
                Result.error(404, "帖子不存在");
    }

    @PostMapping("/{postId}/comment")
    public Result<Comment> addComment(
            @PathVariable Long postId,
            @RequestBody CommentDto commentDto) {

        Comment comment = new Comment();

        User byName = userMapper.findByName(commentDto.getUserName());
        int id = byName.getId();

        comment.setPostId(postId);
        comment.setUserId(id);
        comment.setUserName(commentDto.getUserName());
        comment.setContent(commentDto.getContent());

        return Result.success(commentService.addComment(comment));
    }

    // 获取帖子评论
    @GetMapping("/{postId}/comments")
    public Result<PageResult<Comment>> getComments(
            @PathVariable Long postId,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {

        Page<Comment> page = new Page<>(current, size);
        Page<Comment> result = commentService.pageCommentsByPostId(page, postId);

        PageResult<Comment> pageResult = PageResult.<Comment>builder()
                .list(result.getRecords())
                .total(result.getTotal())
                .current(result.getCurrent())
                .size(result.getSize())
                .pages(result.getPages())
                .build();

        return Result.success(pageResult);
    }

    // 点赞功能
    @PostMapping("/{postId}/like")
    public Result<String> likePost(
            @PathVariable Long postId,
            @RequestParam Integer userId) {

        likeService.likePost(postId, userId);
        return Result.success("点赞成功");
    }

    // 取消点赞
    @DeleteMapping("/{postId}/like")
    public Result<String> unlikePost(
            @PathVariable Long postId,
            @RequestParam Integer userId) {

        likeService.unlikePost(postId, userId);
        return Result.success("已取消点赞");
    }

    // 获取点赞数
    @GetMapping("/{postId}/likes/count")
    public Result<Integer> getLikeCount(@PathVariable Long postId) {
        return Result.success(likeService.getLikeCount(postId));
    }

    @GetMapping("/page")
    public Result<PageResult<Post>> pagePosts(
            PageParam pageParam,
            @RequestParam(required = false) String keyword) {

        // 创建分页对象
        Page<Post> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());

        // 执行分页查询
        Page<Post> result = postService.pagePosts(page, keyword);

        // 为每个帖子添加评论数和点赞数
        result.getRecords().forEach(post -> {
            post.setCommentCount((int) commentService.count(
                    new QueryWrapper<Comment>().eq("post_id", post.getId())
            ));
            post.setLikeCount(likeService.getLikeCount(post.getId()));
        });

        // 构建分页响应对象
        PageResult<Post> pageResult = PageResult.<Post>builder()
                .list(result.getRecords())
                .total(result.getTotal())
                .current(result.getCurrent())
                .size(result.getSize())
                .pages(result.getPages())
                .build();

        return Result.success(pageResult);
    }

    @GetMapping("/page/{username}")
    public Result<PageResult<Post>> getPagePostsByAuthorId(
            PageParam pageParam,
            @PathVariable  String username,
            @RequestParam(required = false) String keyword) {
        Integer authorId = userService.getAuthorIdByUsername(username);
        // 创建分页对象
        Page<Post> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());

        // 执行分页查询
        Page<Post> result = postService.getPagePostsByAuthorId(page, authorId, keyword);

        // 为每个帖子添加评论数和点赞数
        result.getRecords().forEach(post -> {
            post.setCommentCount((int) commentService.count(
                    new QueryWrapper<Comment>().eq("post_id", post.getId())
            ));
            post.setLikeCount(likeService.getLikeCount(post.getId()));
        });

        // 构建分页响应对象
        PageResult<Post> pageResult = PageResult.<Post>builder()
                .list(result.getRecords())
                .total(result.getTotal())
                .current(result.getCurrent())
                .size(result.getSize())
                .pages(result.getPages())
                .build();

        return Result.success(pageResult);
    }
    @GetMapping("/commentlist")
    public ResponseEntity<Result<List<Comment>>> getCommentList(
            @RequestParam(required = false) Integer id) {
        try{
            return ResponseEntity.ok(Result.success(commentService.getCommentList(id)));
        } catch (Exception e){
            logger.error("获取帖子信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error(500,"系统错误，请稍后再试"));
        }
    }
}
